package com.zznj.xzjc;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.luck.picture.lib.tools.ScreenUtils;
import com.vondear.rxtool.RxDeviceTool;
import com.vondear.rxtool.RxIntentTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogSure;
import com.zznj.xzjc.application.APP;
import com.zznj.xzjc.bean.VersionBean;
import com.zznj.xzjc.bean.index.FileData;
import com.zznj.xzjc.bean.index.PushData;
import com.zznj.xzjc.fragment.MainFragment;
import com.zznj.xzjc.fragment.PushMainFragment;
import com.zznj.xzjc.fragment.PersonalCenterFragment;
import com.zznj.xzjc.net.entity.BaseBean;
import com.zznj.xzjc.net.rxjava.HttpMethods;
import com.zznj.xzjc.net.subscribers.ProgressSubscriber;
import com.zznj.xzjc.net.subscribers.SubscriberOnNextListener;
import com.zznj.xzjc.permission.MPermission;
import com.zznj.xzjc.permission.annotation.OnMPermissionDenied;
import com.zznj.xzjc.permission.annotation.OnMPermissionGranted;
import com.zznj.xzjc.permission.annotation.OnMPermissionNeverAskAgain;
import com.zznj.xzjc.utils.NotificationUtil;
import com.zznj.xzjc.utils.statusbar.StatusBarUtil;
import com.zznj.xzjc.widget.FragmentAda;
import com.zznj.xzjc.widget.MyViewPager;
import com.zznj.xzjc.widget.TabPageIndicator;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import okhttp3.FormBody;


public class MainActivity extends AppCompatActivity {
    private void requestBasicPermission() {
        MPermission.with(MainActivity.this).setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS).request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {

    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
        RxToast.normal("部分权限开启失败，可能会影响操作");
    }

    /**
     * 基本权限管理
     */
    private final int BASIC_PERMISSION_REQUEST_CODE = 110;
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };

    @BindView(R.id.main_viewpager)
    MyViewPager mViewPager;
    @BindView(R.id.tab)
    TabPageIndicator tabPageIndicator;
    @BindView(R.id.tishiView)
    View tishiView;


    private String[] titles = {"主页", "消息推送", "我的"};
    private int[] selectTabIcon = {R.mipmap.gyss_tab1_select,
            R.mipmap.gyss_tab4_select,
            R.mipmap.gyss_tab2_select};
    private int[] unSelectTabIcon = {R.mipmap.gyss_tab1_normal,
            R.mipmap.gyss_tab4_normal,
            R.mipmap.gyss_tab2_normal};
    private ArrayList<Fragment> fragList = new ArrayList<Fragment>();
    //退出时的时间
    private long mExitTime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_layout1);
        APP.getInstance().add(this);
        ButterKnife.bind(this);
        StatusBarUtil.setStatusBar(this, true, R.color.transparent, false, false);
        initFragments();
        initViewPager();
        initView();
    }

    private void initPush() {
        //绑定别名
        JPushInterface.resumePush(this);
        JPushInterface.setAlias(this, 1, "");
    }

    //对返回键进行监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出到后台
     */
    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(MainActivity.this, "再按一次进入后台", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            Intent i = new Intent(Intent.ACTION_MAIN);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addCategory(Intent.CATEGORY_HOME);
            startActivity(i);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        fragList.get(mViewPager.getCurrentItem()).onActivityResult(10,RESULT_OK,data);
        super.onActivityResult(requestCode, resultCode, data);

    }

    private void initFragments() {
        MainFragment mainFragment = new MainFragment();
        fragList.add(mainFragment);
        PushMainFragment bmfwFrag = new PushMainFragment();
        fragList.add(bmfwFrag);
        PersonalCenterFragment personalCenterFragment = new PersonalCenterFragment();
        fragList.add(personalCenterFragment);
    }

    private void initViewPager() {
        mViewPager.setStatic(true);
        mViewPager.setAdapter(new FragmentAda(getSupportFragmentManager(), fragList,null));
        tabPageIndicator.setTitles(titles).setNormalTextSize(12)
                .setSelectBgIcon(-1).setUnSelectBgIcon(-1)
                .setSelectTextColor(R.color.tab_menu_text_select)
                .setUnSelectTextColor(R.color.tab_menu_text_normal)
                .setSelectTabIcon(selectTabIcon)
                .setUnSelectTabIcon(unSelectTabIcon)
                .setTabWidth(ScreenUtils.getScreenWidth(this) / titles.length)
                .setTabHeight(ScreenUtils.dip2px(this, 55))
                .setViewPager(mViewPager);
        tabPageIndicator.setOnTabClickListener(new TabPageIndicator.TabClickListener() {
            @Override
            public void onTabClick(String tabTitle) {

            }
        });
        mViewPager.setCurrentItem(0);
    }


    private void initView() {
        requestBasicPermission();
        JPushInterface.setAlias(this,1,"345");
        JPushInterface.resumePush(this);
        //通知权限判断
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //判断是否需要开启通知栏功能
            NotificationUtil.OpenNotificationSetting(this, new NotificationUtil.OnNextLitener() {
                @Override
                public void onNext(int type) {
                    //获取版本信息

                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
        getVersion();
    }

    private void getVersion() {
        SubscriberOnNextListener<BaseBean<FileData>> onNextListener = baseBean -> {
            if(baseBean.getResult() != null){
                initDialogSure(this,baseBean.getResult().getContent());
            }
        };
        FormBody.Builder requestBuilder = new FormBody.Builder()
                .add("versionNo", RxDeviceTool.getAppVersionNo(this)+"");
        FormBody requestBody = requestBuilder.build();
        HttpMethods.getInstance().getVersionInfo(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }

    private void getData() {
        SubscriberOnNextListener<BaseBean<List<PushData>>> onNextListener = baseBean -> {
            if(baseBean.getResult() != null && baseBean.getResult().size() > 0){
                tishiView.setVisibility(View.VISIBLE);
            }else{
                tishiView.setVisibility(View.GONE);
            }
        };
        FormBody.Builder requestBuilder = new FormBody.Builder()
                .add("readStatus", "1")
                .add("page","1");
        FormBody requestBody = requestBuilder.build();
        HttpMethods.getInstance().getMessageList(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }

    /**
     * 跳转系统设置APP权限界面
     *
     * @param mContext
     * @param str
     */
    public static void initDialogSure(final Context mContext, String str) {
        final RxDialogSure rxDialogSure = new RxDialogSure(mContext);
        rxDialogSure.getLogoView().setVisibility(View.GONE);
//        rxDialogSure.getTitleView().setVisibility(View.GONE);
        rxDialogSure.setContent(str);
        rxDialogSure.getContentView().setTextSize(20);
        rxDialogSure.getContentView().setTextColor(ContextCompat.getColor(mContext, com.vondear.rxui.R.color.green_388e3c));
        rxDialogSure.getContentView().setGravity(Gravity.CENTER);
        rxDialogSure.setCanceledOnTouchOutside(false);
        rxDialogSure.setSureListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openBrowser(mContext);
            }
        });
        rxDialogSure.show();
    }

    /**
     * 打开浏览器进行下载
     *
     * @param context 上下文
     * @param url     链接
     */
    public static void openBrowser(Context context) {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(HttpMethods.VERSION_URL));
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            context.startActivity(Intent.createChooser(intent, context.getString(R.string.choice_browser)));
        } else {
            RxToast.normal("链接错误或无浏览器");
        }
    }
}
